package com.websocket.websocket.config;

import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.*;

import java.util.HashMap;
import java.util.Map;

/**
 * https://www.jb51.net/article/145658.htm
 */

/**
 * @author ypz
 * @date 2021/9/6 10:51
 */
@Service
@Slf4j
public class CustomHandler implements WebSocketHandler {
    //在线用户列表
    private static final Map<String,WebSocketSession> users;

    static {
        users = new HashMap<>();
    }
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
      log.info("成功建立连接");
      //解析uri中的用户Id
      String id = session.getUri().toString().split("ID=")[1];
      log.info("用户ID为:{}",id);
      if (id != null){
          users.put(id,session);
          session.sendMessage(new TextMessage("用户"+id+"成功建立socket连接"));
      }
      log.info("系统当前在线人数"+users.size());
    }

    /**
     * 接收websocket消息
     * @param webSocketSession
     * @param webSocketMessage
     * @throws Exception
     */
    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(webSocketMessage.getPayload().toString());
        sendMessageToUser(jsonObject.get("id")+"",new TextMessage("服务器收到了，hello!"));
        //广播信息
        //sendBroadcast(jsonObject.get("id")+"",new TextMessage("广播信息"));
    }

    @SneakyThrows
    public void sendBroadcast(String  id, TextMessage textMessage) {
        WebSocketSession session = null;
        for(String userId : users.keySet()){
            WebSocketSession webSocketSession = users.get(userId);
            if (webSocketSession.isOpen()){
                session.sendMessage(textMessage);
            }
        }
        log.info("系统当前在线人数"+users.size());
    }


    /**
     * 发送信息给指定用户
     */
    @SneakyThrows
    public void sendMessageToUser(String id, TextMessage textMessage) {
        if (users.get(id) == null) return;
        WebSocketSession webSocketSession = users.get(id);
        if (!webSocketSession.isOpen()) return;
        webSocketSession.sendMessage(textMessage);
        log.info("发送信息给用户：{}",id);
        log.info("系统当前在线人数"+users.size());
    }


    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
        if (webSocketSession.isOpen()){
            webSocketSession.close();
        }   
        log.info("连接出错");
        users.remove(getClientId(webSocketSession));
        log.info("系统当前在线人数"+users.size());
    }

    private String getClientId(WebSocketSession webSocketSession) {
        String id = (String) webSocketSession.getAttributes().get("websocket");
        return id;
    }

    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        log.info("连接关闭");
        users.remove(getClientId(webSocketSession));
        log.info("系统当前在线人数"+users.size());
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
